package com.naiterui.ehp.ps.push.service.impl;

import java.util.ArrayList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.ps.push.bean.PushParams;
import com.naiterui.ehp.ps.push.exception.ExceptionCodes;
import com.naiterui.ehp.ps.push.mongo.FailPushRecordDao;
import com.naiterui.ehp.ps.push.service.IChannelPushService;
import com.naiterui.ehp.ps.push.utils.umeng.DoctorIosPusher;

import cn.hutool.core.collection.CollectionUtil;

/**
 * IOSpush服务
 *
 * @author Gll
 * @date 2019-09-02 14:35:18
 * @since 1.0.0
 */
@Component("doctorIosPushService")
public class DoctorIosPushServiceImpl implements IChannelPushService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DoctorIosPushServiceImpl.class);

    @Autowired
    private FailPushRecordDao failPushRecordDao;
    @Autowired
    private DoctorIosPusher iosPusher;

    /**
     * 根据设备token向某个设备发送push
     */
    @Override
    public void sendSingleDevice(PushParams pushParams) throws BusinessException {
        try {
            this.iosPusher.sendIOSUnicast(pushParams.getToken(), pushParams.getMessage(), pushParams.getLinkUrl());
        } catch (Exception e) {
            LOGGER.error("sendSingleDevice fail, pushParams={},error={}", pushParams, e);
            throw new BusinessException(ExceptionCodes.UMENG_PUSH_FAIL);
        }
        /*
        Message pushMessage = this.getIosPushMessage(pushParams);
        PushAppRequest pushAppRequest = new PushAppRequest();
        pushAppRequest.setMessage(pushMessage);
        ArrayList<String> tokenList = new ArrayList<>(1);
        tokenList.add(pushParams.getToken());
        pushAppRequest.setToken_list(tokenList);
        pushAppRequest.setMulti_pkg(true);
        pushAppRequest.setPush_id(pushParams.getUserId() == null ? null : pushParams.getUserId().toString());
        pushAppRequest.setStat_tag(pushParams.getPushTag());
                */
/*
        设置消息离线存储时间（单位为秒）
        */        /*

        pushAppRequest.setExpire_time(pushParams.getExpireTime() == null ? 0 : pushParams.getExpireTime());
        pushAppRequest.setSend_time(DateUtil.formatDate(new Date(System.currentTimeMillis()),
                DateUtil.DATE_TIME_FORMAT));

        PushAppResponse pushResult = ApplePushUtil.pushSingleToken(pushAppRequest);
        if (pushResult != null && pushResult.getRet_code() == ApplePushUtil.XINGE_SERVER_RESULT_SUCCESS) {
            LOGGER.debug("push single 发送成功,pushResult:{}", pushResult);
            return;
        }
        if (pushParams.getReSend() == null || !pushParams.getReSend()) {
                    */
        /*
         * 发送失败 记录失败发送记录
         */        /*

            FailPushRecord failPushRecord = new FailPushRecord();
            failPushRecord.setCreateAt(System.currentTimeMillis());
            failPushRecord.setPushAppRequest(pushAppRequest);
            failPushRecord.setPushAppResponse(pushResult);
            failPushRecord.setResultCode(pushResult.getResult());
            failPushRecord.setPushId(pushAppRequest.getPush_id());
            failPushRecord.setPushSeq(pushAppRequest.getSeq());
            failPushRecord.setToken(pushParams.getToken());
            failPushRecord.setUserId(pushParams.getUserId());
            failPushRecord.setPushParams(pushParams);
            failPushRecord.setQuantityType(FailPushRecord.QUANTITY_TYPE_SINGLE);
            this.failPushRecordDao.saveFailPushRecord(failPushRecord);
        }
        */

    }

    @Override
    public void sendAllDevice(PushParams pushParams) throws BusinessException {
        try {
            this.iosPusher.sendIOSBroadcast(pushParams.getMessage(), pushParams.getLinkUrl());
        } catch (Exception e) {
            LOGGER.error("sendAllDevice fail, pushParams={},error={}", pushParams, e);
            throw new BusinessException(ExceptionCodes.UMENG_PUSH_FAIL);
        }
        /*
        Message pushMessage = this.getIosPushMessage(pushParams);
        PushAppRequest pushAppRequest = new PushAppRequest();
        pushAppRequest.setMessage(pushMessage);
        pushAppRequest.setPush_id(pushParams.getUserId() == null ? null : pushParams.getUserId().toString());
        pushAppRequest.setStat_tag(pushParams.getPushTag());
                */
/*
        设置消息离线存储时间（单位为秒）
        */        /*

        pushAppRequest.setExpire_time(pushParams.getExpireTime() == null ? 0 : pushParams.getExpireTime());

        PushAppResponse pushAppResponse = ApplePushUtil.pushBatchIosDevice(pushAppRequest);

        if (pushAppResponse != null && pushAppResponse.getRet_code() == ApplePushUtil.XINGE_SERVER_RESULT_SUCCESS) {
            LOGGER.debug("push all 发送成功,pushResult:{}", pushAppResponse);
            return;
        }
        if (pushParams.getReSend() == null || !pushParams.getReSend()) {
                    */
        /*
         * 发送失败 记录失败发送记录
         */        /*

            FailPushRecord failPushRecord = new FailPushRecord();
            failPushRecord.setCreateAt(System.currentTimeMillis());
            failPushRecord.setPushAppRequest(pushAppRequest);
            failPushRecord.setPushAppResponse(pushAppResponse);
            failPushRecord.setPushId(pushAppRequest.getPush_id());
            failPushRecord.setQuantityType(FailPushRecord.QUANTITY_TYPE_ALL);
            failPushRecord.setPushParams(pushParams);
            this.failPushRecordDao.saveFailPushRecord(failPushRecord);
        }
        */

    }

    @Override
    public void batchSendDevice(PushParams pushParams, ArrayList<String> deviceList) throws BusinessException {
        if (CollectionUtil.isEmpty(deviceList)) {
            return;
        }
        deviceList.forEach(deviceToken -> {
            try {
                this.iosPusher.sendIOSUnicast(deviceToken, pushParams.getMessage(), pushParams.getLinkUrl());
            } catch (Exception e) {
                LOGGER.error("batchSendDevice fail, pushParams={},deviceToken={},error={}", pushParams, deviceToken, e);
            }
        });

        /*
        Message pushMessage = this.getIosPushMessage(pushParams);
        PushAppRequest pushAppRequest = new PushAppRequest();
        pushAppRequest.setMessage(pushMessage);
        pushAppRequest.setPush_id(pushParams.getUserId() == null ? null : pushParams.getUserId().toString());
        pushAppRequest.setStat_tag(pushParams.getPushTag());
                */
/*
        设置消息离线存储时间（单位为秒）
        */        /*

        pushAppRequest.setExpire_time(pushParams.getExpireTime() == null ? 0 : pushParams.getExpireTime());
                */
/*
        设置发送目标
         */        /*

        pushAppRequest.setToken_list(deviceList);
        PushAppResponse pushAppResponse = ApplePushUtil.pushBatchIosDevice(pushAppRequest);
        if (pushAppResponse != null && pushAppResponse.getRet_code() == ApplePushUtil.XINGE_SERVER_RESULT_SUCCESS) {
            LOGGER.debug("push batch 发送成功,pushResult:{}", pushAppResponse);
            return ApplePushUtil.XINGE_SERVER_RESULT_SUCCESS;
        }
        if (pushParams.getReSend() == null || !pushParams.getReSend()) {
                    */
        /*
         * 发送失败 记录失败发送记录
         */        /*

            FailPushRecord failPushRecord = new FailPushRecord();
            failPushRecord.setCreateAt(System.currentTimeMillis());
            failPushRecord.setPushAppRequest(pushAppRequest);
            failPushRecord.setPushAppResponse(pushAppResponse);
            failPushRecord.setPushId(pushAppRequest.getPush_id());
            failPushRecord.setQuantityType(FailPushRecord.QUANTITY_TYPE_BATCH);
            failPushRecord.setPushParams(pushParams);
            if (pushAppResponse != null) {
                LOGGER.debug("发送结果明细:{}", pushAppResponse.getResult());
            }
            this.failPushRecordDao.saveFailPushRecord(failPushRecord);
        }
        return ApplePushUtil.XINGE_SERVER_RESULT_FAIL;
        */
    }

}
